from django.shortcuts import render, redirect
from app02 import models

# Create your views here.

def depart_list(request):
    """ 部门列表 """
    # 去数据库中获取所有的部门列表
    queryset = models.department.objects.all()
    return render(request, 'depart_list.html', {'depart_list': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request, 'depart_add.html')
    # 获取用户POST提交的数据
    add_title = request.POST.get("title")
    # 保持到数据库
    models.department.objects.create(title=add_title)
    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    nid = request.GET.get('nid')
    models.department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")


# http://127.0.0.1:8000/depart/3/list/
# http://127.0.0.1:8000/depart/9/list/
def depart_edit(request, nid):
    """ 修改部门 """
    # 根据nid,获取数据 [obj,]
    if request.method == "GET":
        row_object = models.department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {"ntitle": row_object.title})

    # 获取用户提交的标题
    etitle = request.POST.get("title")

    # 保持到数据库
    models.department.objects.filter(id=nid).update(title=etitle)
    return redirect("/depart/list/")



